//
//  UIViewController+YY.m
//  YiYunSTP
//
//  Created by 易云物联 on 2019/3/29.
//  Copyright © 2019 yiyuniot. All rights reserved.
//

#import "UIViewController+YY.h"
#import <objc/runtime.h>

typedef void(^ReadyToLoginBlk)(NSString *message);
typedef void(^HaveLoginBlk)(void);
@implementation UIViewController (YY)

- (void)setupForDismissKeyboard
{
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    UITapGestureRecognizer *singleTapGR =
    [[UITapGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(tapAnywhereToDismissKeyboard:)];
    
    __weak UIViewController *weakSelf = self;
    
    NSOperationQueue *mainQuene =[NSOperationQueue mainQueue];
    [nc addObserverForName:UIKeyboardWillShowNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [weakSelf.view addGestureRecognizer:singleTapGR];
                }];
    [nc addObserverForName:UIKeyboardWillHideNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [weakSelf.view removeGestureRecognizer:singleTapGR];
                }];
}

- (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer {
    [self.view endEditing:YES];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}
- (BOOL)prefersStatusBarHidden{
    return NO;
}

//-(UIImage *)navigationBarBackgroundImage {
//    CGSize size = CGSizeMake(YYScreenWidth, YYStatusBarHeight+YYHeight_NavBar());
//    UIImage *bgImg = [UIImage gradientColorImageFromColors:YYGradientColorsNavBarBkgColor gradientType:GradientTypeLeftToRight imgSize:size];
//    return bgImg;
//}

+ (UIViewController *)yy_rootViewController{

    UIWindow* window = UIApplication.sharedApplication.delegate.window;
//    NSAssert(window, @"The window is empty");
    return window.rootViewController;
}

+ (UIViewController *)yy_visibleViewController {
    
    UIViewController* currentViewController = [self yy_rootViewController];
    BOOL runLoopFind = YES;
    while (runLoopFind) {
        if (currentViewController.presentedViewController) {
            currentViewController = currentViewController.presentedViewController;
        } else {
            if ([currentViewController isKindOfClass:[UINavigationController class]]) {
                currentViewController = ((UINavigationController *)currentViewController).visibleViewController;
            } else if ([currentViewController isKindOfClass:[UITabBarController class]]) {
                currentViewController = ((UITabBarController* )currentViewController).selectedViewController;
            } else {
                break;
            }
        }
    }
    return currentViewController;
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    if ([navigationController isKindOfClass:[UIImagePickerController class]]) {
        //iOS11 UIImagePickerControllerEditedImage 异常问题
        navigationController.navigationBar.translucent = YES;
    }
}

-(void)setCallBackReloadData:(void (^)(void))callBackReloadData{
    [self willChangeValueForKey:@"callBackReloadData"];
    objc_setAssociatedObject(self, "callBackReloadData", callBackReloadData, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self didChangeValueForKey:@"callBackReloadData"];
}

-(void (^)(void))callBackReloadData{
    return objc_getAssociatedObject(self, "callBackReloadData");
}

-(void)accountCheckWithAccountState:(UserAccountState)state callbackRefresh:(BOOL)refresh callBack:(nullable void(^)(void))callBackReloadData{
    switch (state) {
        case UserAccountStateTokenFailure:
            [self alertWithMessage:@"登录账户失效，请重新登录" callbackRefresh:refresh reloadData:callBackReloadData];
            break;
        case UserAccountStateNoLogin:
            [self alertWithMessage:@"请登录您的账号" callbackRefresh:refresh reloadData:callBackReloadData];
            break;
    }
}

-(void)alertWithMessage:(NSString *)message callbackRefresh:(BOOL)refresh reloadData:(void(^)(void))callBackReloadData{
    __weak typeof(self) weakSelf = self;
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *rightAction = [UIAlertAction actionWithTitle:@"去登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (refresh) {
            weakSelf.callBackReloadData = callBackReloadData;
//            [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reloaddataSource:) name:kYYNotification_LoginSuccess object:@"login"];
        }
        UIViewController *viewController  = [[NSClassFromString(@"YYLoginViewController") alloc] init];
        [self getAllProperties:viewController];
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:viewController];
        UIViewController *root = [UIApplication sharedApplication].keyWindow.rootViewController;
        [root presentViewController:nav animated:YES completion:nil];
    }];
//    UIAlertAction *cancleActions = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action){
//    }];
//    [alertController addAction:cancleActions];
    [alertController addAction:rightAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

-(void)reloaddataSource:(NSNotification *)notificat{
    if ([notificat.object isEqualToString:@"login"]) {
        !self.callBackReloadData ?: self.callBackReloadData();
        [[NSNotificationCenter defaultCenter]removeObserver:self];
    }
}

/**
 获取指定类的变量
 @param cls 被获取变量的类
 @return 变量名称集合 [NSString *]
 */
#pragma mark -- private
-(void)getAllProperties:(UIViewController *)viewController{
    unsigned int a;
    Ivar * properties = class_copyIvarList(object_getClass(viewController), &a);
    for (unsigned int i = 0; i < a; i++) {
        Ivar i_v = properties[i];
        NSString *property = [NSMutableString stringWithFormat:@"%s", ivar_getName(i_v)];
        NSLog(@"property:%@",property);
        if ([property isEqualToString:@"_dimiss"]) {
            [viewController setValue:@"dimiss" forKey:property];
            break;
        }
    }
    free(properties);
}

@end
